package com.example.environment.tools;

import com.example.environment.service.AuthService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private AuthService authService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String authorizationHeader = request.getHeader("Authorization");

        System.out.println("Authorization Header: " + authorizationHeader); // 打印请求头以调试

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            System.out.println("A: "+token); // 打印请求头以调试
            System.out.println("A: "+authService.validate(token).toString()); // 打印请求头以调试
            if (authService.validate(token).getCode() == 0) {
                String id = JwtUtil.getStaffId(token);
                System.out.println("B: "+id); // 打印请求头以调试
                // 将用户ID存储到请求属性中，后续可以用来鉴权
                request.setAttribute("id", id);
            }
        }
        System.out.println("no answer: " + authorizationHeader); // 打印请求头以调试
        filterChain.doFilter(request, response);
    }

}
